<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">学历信息</h4>
      </a-row>
      <a-col :span="8">
        <a-form-item label="学历证明" v-bind="validateInfos.instructions" style="margin-left: 10px;">
          <j-upload v-model:value="formData.instructions" :disabled="disabled" :max-count="1"></j-upload>
        </a-form-item>
      </a-col>
      <a-row>
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">荣誉证书</h4>
      </a-row>

      <!-- 插入表格 -->
      <BasicTable @register="registerTable" :columns="columnsHonor" :dataSource="honValue" :showActionColumn="false"
        style="margin-left: 10px;">
        <!-- <div :style="height:20px"> -->
        <!--字段回显插槽-->
        <template #htmlSlot="{ text }">
          <div v-html="text"></div>
        </template>
        <!--上传组件插槽-->
        <template #uploadSlot="{ record }">
          <a-form-item>
            <j-upload v-model:value="record.certFile" style="width: 150px;" :disabled="disabled"></j-upload>
          </a-form-item>
        </template>
        <template #action="{ record }">
          <TableAction :actions="getTableActionA(record)" />
        </template>
        <!-- </div> -->

      </BasicTable>
      <div>
        <a-button type="primary" @click="addHon" class="icons-list" style="margin-left: 35px;">
          <PlusCircleOutlined />
        </a-button>
      </div>

      <a-row style="margin-top: 10px;">
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">资质证书</h4>
      </a-row>

      <BasicTable @register="registerTable" :columns="columnsFla" :dataSource="flaValue" style="margin-left: 10px;">

        <!--字段回显插槽-->
        <template #htmlSlot="{ text }">
          <div v-html="text"></div>
        </template>
        <template #uploadSlotTwo="{ record }">
          <a-form-item>
            <j-upload v-model:value="record.certFile" style="width: 150px;" :disabled="disabled"></j-upload>
          </a-form-item>
        </template>
        <template #action="{ record }">
          <TableAction :actions="getTableActionB(record)" />
        </template>
        <!-- 资质名称列插槽 -->
        <template #qualifications="{ record }">

          <j-select-input  v-model:value="record.certName" :showSearch="true"  :allowClear="true" :options="options" style="width: 100%;"
              :disabled="disabled" />
        </template>
      </BasicTable>
      <div>
        <a-button type="primary" @click="addFla" class="icons-list" style="margin-left: 35px;">
          <PlusCircleOutlined />
        </a-button>
      </div>
    </a-form>
  </a-spin>
</template>


<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, watch } from 'vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { getValueType } from '/@/utils';
import { saveOrUpdate, saveOrUpdateFlair } from '../SysUser.api';
import { Form } from 'ant-design-vue';
import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
import { useListPage } from '/@/hooks/system/useListPage';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { columnsHonor, columnsFla } from '../../../lab/labUser/cert/LabCert.data';
import { countHon, countFla, deleteOne, countEdu, getCert } from '../../../lab/labUser/cert/LabCert.api';
import { PlusCircleOutlined } from '@ant-design/icons-vue';
import { onMounted } from 'vue';
import JSelectInput from '../../../../../src/components/Form/src/jeecg/components/JSelectInput.vue';




const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => { } },
  formBpm: { type: Boolean, default: true }
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  realname: '',
  avatar: '',
  birthday: '',
  sex: undefined,
  email: '',
  phone: '',
  post: '',
  userIdentity: undefined,
  educational: '',
  technicalTitle: '',
  cardType: '',
  cardNumber: '',
  specialty: '',
  startWorkDate: '',
  workYear: undefined,
  vitae: '',
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 7 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 12 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = {
};
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: true });

// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});

//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    canResize: true,
    useSearchForm: false,
    actionColumn: {
      width: 120,
      fixed: 'right',
    },
    showIndexColumn: true,
    showTableSetting: false,
    pagination: false,

  },

});
const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource },] = tableContext;

const options =  ref<Array<{ name: string }>>();; // 定义 qualificationOptions 数组  下拉框
onMounted(async () => {
  const res = await getCert();
   console.log("res",res);
   options.value = res.map(item => {
    return {
      value: item.flaName,
      label: item.flaName
    }
  });
  console.log("options",options);
})
const value = ref<string[]>([]);
const handleChange = (value: []) => {
  console.log(`selected ${value}`);
};
watch(value, () => {
  console.log('value', value.value);
});




function generateRandomId() {
  return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
function addHon(record) {

  honValue.value.push({
    id: generateRandomId(),
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    certName: null,
    certFile: null,
    certType: "荣誉",
  });
}

function addFla(record) {
  flaValue.value.push({
    id: generateRandomId(),
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    certName: record.certName,
    certFile: null,
    certType: "资质",
  });
   
}
/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 操作栏
 */
function getTableActionA(record) {
  return [
    {
      label: '删除',
      color: 'error',
      popConfirm: {
        title: '是否确认删除',
        width: 155,
        confirm: handleDeleteA.bind(null, record),
      }
    }
  ];
}
/**
 * 操作栏
 */
function getTableActionB(record) {
  return [
    {
      label: '删除',
      color: 'error',
      popConfirm: {
        title: '是否确认删除',
        width: 155,
        confirm: handleDeleteB.bind(null, record),
      }
    }
  ];
}
/**
 * 删除事件
 */
async function handleDeleteA(record) {

  honValue.value = honValue.value.filter((hon) => hon.id !== record.id)
}
/**
 * 删除事件
 */
async function handleDeleteB(record) {
  flaValue.value = flaValue.value.filter((fla) => fla.id !== record.id)
}

/**
 * 编辑
 */
const honValue = ref();
const flaValue = ref();
async function edit(record) {
  honValue.value = [];
  flaValue.value = [];
  formData.instructions = [];
  Object.assign(formData, record);
  const hon = await countHon({ id: record.id });
  honValue.value = hon;
  const fla = await countFla({ id: record.id });
  flaValue.value = fla;
  const edu = await countEdu({ id: record.id });
  if(edu!==null){
    formData.instructions = edu.certFile;//学历
  }
  

  // nextTick(() => {
  //   resetFields();
  //   //赋值
  //   Object.assign(formData, record);
  // });
}
// 计算从事本技术领域年限
function changeDate() {
  let startWorkDate = formData.startWorkDate
  let today = formatDate(new Date().toLocaleDateString());
  //从事本技术领域开始年月
  let oYear = startWorkDate.slice(0, 4);
  let oMon = startWorkDate.slice(5, 7);
  //当前年月
  let nYear = today.slice(0, 4);
  let nMon = today.slice(6, 7);
  //计算相差年月
  let year = parseInt(nYear) - parseInt(oYear);
  let mon = parseInt(nMon) - parseInt(oMon);
  var Ynum = parseInt(((year * 12 + mon) / 12));
  var Mnum = ((year * 12 + mon) % 12);

  if (Number(Mnum) <= 6) {
    formData.workYear = Ynum + 0.5;
  } else {
    formData.workYear = Ynum + 1;
  }
}

// 日期格式转换成YYYY-MM-DD
function formatDate(date) {
  var d = new Date(date),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear();

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return [year, month, day].join('-');
}
/**
 * 提交数据
 */
async function submitForm() {

  // 触发表单验证
  await validate();
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }


  // 将两张表格中的数据添加到表单数据中
  const hon = JSON.parse(JSON.stringify(honValue.value));
  const fla = JSON.parse(JSON.stringify(flaValue.value));
  model.honValue = hon;
  model.flaValue = fla;
  // 将学历证明上传组件的信息添加到表单数据中
  model.educat = formData.instructions;
 console.log("model",model);
 
  await saveOrUpdateFlair(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}


defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  min-height: 500px !important;
  overflow-y: auto;
  padding: 24px 24px 24px 24px;
}


.antd-modal-divider {
  width: 2px;
  height: 16px;
  background: #009688;
  border-radius: 0px 0px 0px 0px;
  opacity: 1;
}

.hClass {
  width: 60px;
  height: 20px;
  font-size: 14px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 550;
  color: #009688;
  line-height: 14px;
}

.ant-input {
  width: 200px;
  height: 32px;
  border-radius: 4px 4px 4px 4px;
  opacity: 1;
  border: 1px solid #DDDDDD;
}

.ant-picker {
  width: 200px !important;
  height: 32px;
  border-radius: 4px 4px 4px 4px;
  opacity: 1;
  border: 1px solid #DDDDDD;
}

:deep(.ant-form-item-control-input) {
  width: 200px !important;
}

//
.icons-list :deep(.anticon) {
  margin-right: 1px;
  font-size: 24px;
  margin-top: -5px;
  // top: -20px;
}
</style>
